﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Common;
using Controllers.Extend;
using Controllers.Filter;
using Model.Sys.Config;
using ViewModel;

namespace Controllers.Areas.Power.Controllers
{
    public class ManagerController : UserBaseController
    {
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            cookieName = CookieConfig.UserInfoLoginCookieName;
            base.OnAuthorization(filterContext);

            if (loginUser == null)
            {
                if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new JsonResult()
                    {
                        ContentEncoding = Encoding.UTF8,
                        Data = new ResultModel
                        {
                            Pass = false,
                            Msg = "对不起，您的身份验证过时，请重新登录。"
                        },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }
                else
                {
                    filterContext.Result = new ContentResult() { Content = "<script>alert('对不起，您的身份验证过时，请重新登录。');top.location='/Login/Index';</script>" };
                }
            }
        }

        /// <summary>
        /// 菜单管理列表页面
        /// </summary>
        /// <param name="powerId"></param>
        /// <returns></returns>
        [Power(PowerId = "01000300")]
        public ActionResult Index(string powerId)
        {
            ViewData["powerId"] = powerId;
            return View();
        }

        /// <summary>
        /// 菜单管理列表页面的列表查询
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public ActionResult Search(DataTable dt)
        {
            int total;
            List<Model.Database.Power> treeSortPowerList = new List<Model.Database.Power>();

            IQueryable<Model.Database.Power> powerIq = CurrentBllSession.PowerBll.GetIQueryable();
            total = powerIq.Count();
            List<Model.Database.Power> powerList = powerIq.ToList();
            TreeSortList(powerList,treeSortPowerList,"0");
            dt.recordsTotal = total;
            dt.recordsFiltered = total;
            dt.data = treeSortPowerList;

            return Json(dt);
        }

        /// <summary>
        /// 增加菜单页面
        /// </summary>
        /// <returns></returns>
        [Power(PowerId = "01000301")]
        public ActionResult Add()
        {
            return View();
        }

        /// <summary>
        /// 增加菜单页面的树状菜单
        /// </summary>
        /// <returns></returns>
        public ActionResult MenuList()
        {
            IQueryable<Model.Database.Power> powerIq=CurrentBllSession.PowerBll.GetIQueryable();
            List<Model.Database.Power> powerList = powerIq.ToList();
            List<ZTreeModel> menuList = MakeMenuList(powerList);
            menuList.Insert(0, new ZTreeModel() { id = "0", name = "父级" });

            return Json(menuList);
        }

        /// <summary>
        /// 增加菜单页面的提交
        /// </summary>
        /// <param name="pmPower"></param>
        /// <returns></returns>
        public ActionResult AddSubmit(Model.Database.Power pmPower)
        {
            ResultModel rm = new ResultModel();

            if ((!string.IsNullOrEmpty(pmPower.ParentId)) && (!string.IsNullOrEmpty(pmPower.PowerName)))
            {
                if (!pmPower.IsMenu && string.IsNullOrEmpty(pmPower.Url))
                {
                    rm.Pass = false;
                    rm.Msg = "按钮必须填写请求路径";
                }
                else
                {
                    Model.Database.Power power = pmPower;
                    power.ParentId = pmPower.ParentId.Split(',').FirstOrDefault();
                    power.PowerId = MakePowerId(pmPower.ParentId, pmPower.IsMenu);
                    if (!pmPower.Sort.HasValue)
                    {
                        power.Sort = MakeSort(pmPower.ParentId);
                    }
                    power.AddTime = DateTime.Now;
                    CurrentBllSession.PowerBll.Add(power);
                    rm.Pass = true;
                    rm.Msg = "添加成功，重新登录后，刷新菜单";
                }
            }
            else
            {
                rm.Pass = false;
                rm.Msg = "请填写完整信息";
            }

            return Json(rm);
        }

        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="idArrStr"></param>
        /// <returns></returns>
        [Power(PowerId = "01000302")]
        public ActionResult Delete(string idArrStr)
        {
            ResultModel rm = new ResultModel();

            string[] idArr = idArrStr.Split(',');
            string[] systemPowerId = new string[]
            {
                "0100",
                "01000100","01000101","01000102","01000103","01000104","01000105","01000106",
                "01000200","01000201","01000202","01000203","01000204",
                "01000300","01000301","01000302","01000303","01000304",
                "01000400","01000401","01000402","01000403","01000404",
                "01000500","01000501","01000502","01000503","01000504","01000505","01000506",
                "01000600","01000601","01000602",
                "01000700",
            };
            bool illegal = false;//非法删除
            foreach (var id in idArr)
            {
                if (systemPowerId.Contains(id))
                {
                    illegal = true;
                    break;
                }
            }
            if (!illegal)
            {
                try
                {
                    CurrentBllSession.PowerBll.ListDelete(idArr);
                    rm.Pass = true;
                    rm.Msg = "删除成功";
                }
                catch (Exception e)
                {
                    rm.Pass = false;
                    rm.Msg = "对不起，删除失败";
                }
            }
            else
            {
                rm.Pass = false;
                rm.Msg = "非法删除，删除失败";
            }
            
            return Json(rm);
        }

        /// <summary>
        /// 修改菜单页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Power(PowerId = "01000303")]
        public ActionResult Edit(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                Model.Database.Power power = CurrentBllSession.PowerBll.GetEntity(id);
                return View(power);
            }
            else
            {
                return Content("id参数无效");
            }
        }

        /// <summary>
        /// 修改菜单页面的提交
        /// </summary>
        /// <param name="pmPower"></param>
        /// <returns></returns>
        public ActionResult EditSubmit(Model.Database.Power pmPower)
        {
            ResultModel rm = new ResultModel();

            if ((!string.IsNullOrEmpty(pmPower.PowerName)))
            {
                Model.Database.Power powerOld = CurrentBllSession.PowerBll.GetEntity(pmPower.PowerId);
                powerOld.PowerName = pmPower.PowerName;
                powerOld.Url = pmPower.Url;
                powerOld.IsPost = pmPower.IsPost;
                powerOld.IsMenu = pmPower.IsMenu;
                powerOld.MenuIcon = pmPower.MenuIcon;
                powerOld.ControllerName = pmPower.ControllerName;
                powerOld.ActionName = pmPower.ActionName;
                powerOld.Description = pmPower.Description;
                powerOld.Sort = pmPower.Sort;
                powerOld.ModifyTime = DateTime.Now;
                CurrentBllSession.PowerBll.Update(powerOld);
                rm.Pass = true;
                rm.Msg = "保存成功";
            }
            else
            {
                rm.Pass = false;
                rm.Msg = "请填写必要信息";
            }

            return Json(rm);
        }

        /// <summary>
        /// 查看菜单页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Power(PowerId = "01000304")]
        public ActionResult View(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                Model.Database.Power power = CurrentBllSession.PowerBll.GetEntity(id);
                return View(power);
            }
            else
            {
                return Content("id参数无效");
            }
        }

        /// <summary>
        /// 查看菜单页面的树状菜单（包括按钮显示）
        /// </summary>
        /// <returns></returns>
        public ActionResult MenuBtnList()
        {
            IQueryable<Model.Database.Power> powerIq = CurrentBllSession.PowerBll.GetIQueryable();
            List<Model.Database.Power> powerList = powerIq.ToList();
            List<ZTreeModel> menuBtnList = MakeMenuBtnList(powerList);

            return Json(menuBtnList);
        }

        #region 私有方法
        /// <summary>
        /// 制作排序Sort
        /// </summary>
        private int MakeSort(string parentId)
        {
            int sort = 1;

            Model.Database.Power sameLevelNewestPower = CurrentBllSession.PowerBll.GetIQueryable()
                                                .Where(a => a.ParentId == parentId)
                                                .OrderByDescending(a => a.PowerId)
                                                .FirstOrDefault();
            if (sameLevelNewestPower != null)
            {
                if (sameLevelNewestPower.Sort.HasValue)
                {
                    sort = sameLevelNewestPower.Sort.Value + 1;
                }
            }

            return sort;
        }

        /// <summary>
        /// 制作权限Id(支持七级菜单的ID制作)
        /// 这里从源头上支持了按钮的按钮的权限的控制，但是实际操作中需要页面上操作配合：1.自动生成按钮的按钮的html代码（样式固定）2.手动取写html代码（样式自定义）
        /// </summary>
        private string MakePowerId(string parentId,bool isMenu)
        {
            string powerId = null;
            int parentLevel=parentId.Length/4;//父亲层级
            int level=parentId.Length/4+1;//菜单层级
            Model.Database.Power sameLevelNewestPower = CurrentBllSession.PowerBll.GetIQueryable()//同层级最新权限
                                            .Where(a => a.ParentId == parentId)
                                            .OrderByDescending(a => a.PowerId)
                                            .FirstOrDefault();

            if (isMenu)//菜单Id
            {
                if (sameLevelNewestPower != null)
                {
                    int length=sameLevelNewestPower.PowerId.Length;
                    string pre=sameLevelNewestPower.PowerId.Substring(0, length - 4);//前面相同的权限Id部分
                    string nextTemp = sameLevelNewestPower.PowerId.Substring(length - 4, 4);
                    int nextTempInt=nextTemp.ToInt32Req()+100;
                    string next = nextTempInt.ToString(new StringBuilder().Append("0000").ToString());//后面计算后的权限Id部分
                    powerId = pre + next;
                }
                else
                {
                    powerId = parentId + "0100";
                }
            }
            else//按钮Id
            {
                bool parentIsBtn = !CurrentBllSession.PowerBll.GetEntity(parentId).IsMenu;

                if (parentIsBtn)//父级菜单为按钮
                {
                    if (sameLevelNewestPower != null)
                    {
                        string[] abcArr=new []{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
                        int length = sameLevelNewestPower.PowerId.Length;
                        string pre = sameLevelNewestPower.PowerId.Substring(0, length - 1);//前面相同的权限Id部分
                        string nextTemp = sameLevelNewestPower.PowerId.Substring(length - 1, 1);
                        int sameLevelNewestPowerIndex=Array.IndexOf(abcArr, nextTemp);
                        string next = abcArr[sameLevelNewestPowerIndex+1];//后面计算后的权限Id部分
                        powerId = pre + next;
                    }
                    else
                    {
                        powerId = parentId + "A";
                    }
                }
                else//父级菜单非按钮
                {
                    if (sameLevelNewestPower != null)
                    {
                        int length = sameLevelNewestPower.PowerId.Length;
                        string pre = sameLevelNewestPower.PowerId.Substring(0, length - 2);//前面相同的权限Id部分
                        string nextTemp = sameLevelNewestPower.PowerId.Substring(length - 2, 2);
                        int nextTempInt = nextTemp.ToInt32Req() + 1;
                        string next = nextTempInt.ToString(new StringBuilder().Append("00").ToString());//后面计算后的权限Id部分
                        powerId = pre + next;
                    }
                    else
                    {
                        powerId = parentId.TrimEnd('0')+"01";
                    }
                }
            }

            return powerId;
        }

        /// <summary>
        /// 制作菜单集合
        /// </summary>
        private List<ZTreeModel> MakeMenuList(List<Model.Database.Power> powerList)
        {
            List<Model.Database.Power> treeSortList = new List<Model.Database.Power>();
            List<ZTreeModel> menuList = new List<ZTreeModel>();

            TreeSortList(powerList, treeSortList,"0");
            foreach (var power in treeSortList)
            {
                ZTreeModel menu = new ZTreeModel() { id = power.PowerId, pId = power.ParentId, name = power.PowerName };
                menuList.Add(menu);
            }

            return menuList;
        }

        /// <summary>
        /// 制作菜单按钮集合
        /// </summary>
        private List<ZTreeModel> MakeMenuBtnList(List<Model.Database.Power> powerList)
        {
            List<Model.Database.Power> treeSortList = new List<Model.Database.Power>();
            List<ZTreeModel> menuBtnList = new List<ZTreeModel>();

            TreeSortList(powerList, treeSortList,"0");
            foreach (var power in treeSortList)
            {
                ZTreeModel menu = new ZTreeModel() { id = power.PowerId, pId = power.ParentId, name = power.PowerName };
                menuBtnList.Add(menu);
            }

            return menuBtnList;
        }

        /// <summary>
        /// 树状排序集合（递归）
        /// </summary>
        private void TreeSortList(List<Model.Database.Power> powerList, List<Model.Database.Power> treeSortPowerList, string parentId)
        {
            foreach (var power in powerList.Where(a=> a.ParentId == parentId).OrderBy(a => a.Sort))//菜单
            {
                treeSortPowerList.Add(power);
 
                TreeSortList(powerList, treeSortPowerList, power.PowerId);
            }
        }
        #endregion
        

    }
}
